const QUEUE_LIST: any[] = [];

//添加请求队列
export const addQueue = ({ url, options }) => {
  if (url === '/api/message/list') {
    return false;
  }
  const { data, params } = options;
  const par = data ? data : (params ? params : {});
  if (par && par.notQueue) {
    return false;
  }
  const newRequest = JSON.stringify({ url, params: par });
  for (let i = QUEUE_LIST.length - 1; i >= 0; i -= 1) {
    if (url === QUEUE_LIST[i].url) {
      if (QUEUE_LIST[i].request == newRequest) {
        return true;
      }
    }
  }
  QUEUE_LIST.push({
    request: newRequest,
    url,
  });
  return false;
}
//删除队列
export const removeQueue = ({ url, options }) => {
  if (url === '/api/message/list') {
    return false;
  }
  try {
    // get 有params， post 有data
    const { data, params } = options;
    let handleUrl = url;
    const par = data ? data : (params ? params : {});
    if (par !== {}) {
      //剔除url上面带有的params参数，为了防止query参数又加在路径上又加在params里面
      const paramsKeys = Object.keys(params);
      let handleUrlArr = handleUrl.split('&');
      //循环把params中的参数剔除
      paramsKeys.forEach((paraKey) => {
        const stockIndex = handleUrlArr.findIndex((item) => item.includes(`${paraKey}=`));
        if (stockIndex !== -1) {
          const val = handleUrlArr[stockIndex].replace(`${paraKey}=${params[paraKey]}`, '');
          handleUrlArr[stockIndex] = val;
        }
      });
      //过滤是空的
      handleUrlArr = handleUrlArr.filter(item => item);
      handleUrl = handleUrlArr.join('&');
      const markIndex = handleUrl.indexOf('?');
      //可能出现剔除完以后只剩下‘？’
      if (markIndex === handleUrl.length - 1) {
        handleUrl = handleUrl.replace('?', '');
      }
    }
    const newRequest = JSON.stringify({
      url: handleUrl,
      params: par || {},
    });
    const index = QUEUE_LIST.findIndex((d) => d.request === newRequest);
    if (index !== -1) {
      QUEUE_LIST.splice(index, 1);
    }
    return true;
  } catch (error) {
    return false
  }
}